package eu.webhib.webblog.gui.controller;

import eu.webhib.frmwrk.jsf.base.EditBaseController;
import eu.webhib.frmwrk.jsf.utils.JsfUtil;
import eu.webhib.webblog.application.ApplMail;
import eu.webhib.webblog.gui.application.GuiApplication;
import eu.webhib.webblog.domain.User;
import eu.webhib.webblog.service.factory.ServiceFactory;
import eu.webhib.webblog.service.intf.UserService;
import javax.faces.bean.*;
import javax.faces.event.*;
import org.apache.log4j.Logger;

/**
 * Controller of the User Registration Confirmation page
 */
@ManagedBean(name = "regconf")
@SessionScoped
public class RegisterConfirm extends EditBaseController {

   private static final Logger log = Logger.getLogger(RegisterConfirm.class);
   private static UserService userService = ServiceFactory.getUserService();
   //
   private boolean registerConfirmed = false;

   public boolean isRegisterConfirmed() {
      return registerConfirmed;
   }

   //
   // Registration confirmation -----------------------------------
   //
   public void registerConfirmListener(ComponentSystemEvent event) {
      log.info("registerConfirmListener");
      new EditListenerClosure() {

         @Override
         protected void run(ComponentSystemEvent event) {

            if (GuiApplication.isAuthenticated()) {
               JsfUtil.sendRedirect(GuiApplication.getNotAtLoggedInStatePageURI());
               return;
            }
            registerConfirmed = checkRegisterConfirmUser();
            if (registerConfirmed) {
               setInfoMessage("info_registerconfirm_ok");
            } else {
               setInfoMessage("error_registerconfirm");
            }

         }
      }.start(event);
   }

   private boolean checkRegisterConfirmUser() {
      String confirmSecret = JsfUtil.getRequestParam(ApplMail.emailConfirmUrlParam);
      log.debug("confirmSecret: " + confirmSecret);
      if (confirmSecret == null) {
         return false;
      }
      // lookup user by confirmation secret
      User user = userService.findByAttributeSingle("confirmSecret", confirmSecret);
      if (user == null) {
         log.warn("no user found for confirmSecret");
         return false;
      }
      // check register confirmation for this user
      if (!user.checkRegisterConfirm()) {
         log.warn("user not in right status");
         return false;
      }
      // set registeration confirmed for this user
      user.setRegisterConfirmed();
      userService.save(user);
      return true;
   }

   // Registration confirmation successful
   public String registerConfirmedContinueLoginAction() {
      // go to login page
      JsfUtil.sendRedirect(GuiApplication.getLoginPageURI());
      registerConfirmed = false;
      return null;
   }

   // Registration confirmation not successful
   public String registerConfirmedErrorAction() {
      JsfUtil.sendRedirect(GuiApplication.getHistroyPageURI());
      return null;
   }
}
